package last.fm;

/***
 * @author Ragnvald Fuglestein
 */

import java.util.List;

import baseStructure.Artist;
import baseStructure.Log;
import baseStructure.SortedList;
import baseStructure.Track;
import library.Library;

public class MergeLastFmTracks implements LastFmTrackCallback {
	private static MergeLastFmTracks instance;
	static {
		instance = new MergeLastFmTracks();
	}
	public static MergeLastFmTracks getInstance() {
		return instance;
	}
	
	private MergeLastFmTracks() { }
	
	@Override public void lastFmTracks(List<LastFmTrackAddon> tracks) {
		for (LastFmTrackAddon track : tracks) {
			if (track == null) try {
				Log.d("LastFmTracks");
				Thread.sleep(2000);
				System.exit(-1);
			} catch (InterruptedException e) { }
			else lastFmTrack(track);
		}
	}

	@Override public void lastFmTrack(LastFmTrackAddon track) {
		SortedList<Track> tracks = new SortedList<>();
		Library.getInstance().getTracks(tracks, track.toSearch());
		if (tracks.size() > 0) {
			for (Track t : tracks) {
				if (t == null) try {
					Log.d("LastFmTrack");
					Thread.sleep(2000);
					System.exit(-1);
				} catch (InterruptedException e) { }
				LastFmTrackAddon addon = (LastFmTrackAddon) t.getAddon(LastFmTrackAddon.ADDON_NAME);
				if (addon == null) {
					t.addAddon(track);
				} else {
					addon.merge(track);
				}
			}
		} else {
			Artist artist = track.toArtist();
			artist.addTrack(track.toTrack());
			Library.getInstance().mergeArtist(artist);
		}
	}
}
